import { toRaw} from 'vue'

// 分页函数
interface Options {
    tableData: {
        loading: boolean
        tableList: any[]
        queryParams?:  Record<any, any>
        tableParams: { 
            page_num: number
            page_limit: number
            page_total: number
        }
        extend?: Record<any, any>
    },
    apiData: (_arg: any) => Promise<any> 
}

export function usePage(options: Options) {

    const { tableData, apiData} = options

    // 保存查询初始参数
    const paramsInit: Record<any, any> = Object.assign({}, toRaw(tableData.queryParams))

    // 请求分页接口
    const getTableList = () => {
        tableData.loading = true
        return apiData({
            page_num: tableData.tableParams.page_num,
            page_limit: tableData.tableParams.page_limit,
            ...tableData.queryParams
        })
            .then((res: any) => {
                tableData.tableParams.page_total = res?.page_total || 0
                tableData.tableList = res?.list || []
                tableData.extend = res?.extend || []
                return Promise.resolve(res)
            })
            .catch((err: any) => {
                return Promise.reject(err)
            })
            .finally(() => {
                tableData.loading = false
            })
    }
    // 列表搜索
    const searchTable = () => {
        getTableList()
    }
    // 重置参数
    const resetQuery = () => {
        // 重置为初始参数
        Object.keys(paramsInit).forEach((item) => {
            tableData.queryParams[item] = paramsInit[item]
        })
        tableData.tableParams.page_num = 1
        getTableList()
    }

    return {
        getTableList,
        searchTable,
        resetQuery
    }
}
